package com.example.administrator.androidros.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.example.administrator.androidros.R;
import com.example.administrator.androidros.adapter.SceneDetailsAdapter;
import com.example.administrator.androidros.base.BaseActivity;
import com.example.administrator.androidros.net.HttpUtils;
import com.example.administrator.androidros.utils.AgentConstants;
import com.example.administrator.androidros.utils.AgentSharedPreferences;
import com.example.administrator.androidros.utils.DisplayHelper;
import com.example.administrator.androidros.utils.ServerConstants;
import com.example.administrator.androidros.widget.CustomDialog;
import com.example.administrator.androidros.widget.CustomPopupMenu;
import com.example.administrator.androidros.widget.CustomTipDialog;
import com.example.administrator.androidros.widget.EditDialog;
import com.hhc.netty.DeviceModel;
import com.hhc.netty.NettyBaseMsg;
import com.hhc.netty.NettyClient;
import com.hhc.netty.NettyReplyStatusMsg;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class SceneDetailsActivity extends BaseActivity {
    private static final String TAG = "hhc";
    @BindView(R.id.common_head_more)
    protected ImageView common_head_more;
    @BindView(R.id.common_head_title)
    protected TextView common_head_title;
    @BindView(R.id.activity_scene_detail_list)
    protected RecyclerView activity_scene_detail_list;
    private String title;
    private String sceneMasterId;
    private List<Integer> moreIconList = new ArrayList<>();//更多
    private List<String> moreTitleList = new ArrayList<>();
    private SceneDetailsAdapter sceneDetailsAdapter;
    protected List<DeviceModel> data = new ArrayList();
    private int mPosition = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_scene_details);
    }

    @Override
    protected void initData() {
        getIntentData();
        initCommonHeader();
        initMoreData();
        initView();
    }

    @Override
    protected void onFailure(int requestCode, Object object) {
        showToast(R.string.common_response_failure);
        stopTipDialog();
    }

    @Override
    protected void onSuccess(int requestCode, Object object) {
        stopTipDialog();
        if (object != null) {
            switch (requestCode) {
                //获取设备列表
                case 1001:
                    DeviceModel[] deviceModels = (DeviceModel[]) HttpUtils.getData(object, DeviceModel[].class);
                    if (deviceModels != null) {
                        data = Arrays.asList(deviceModels);
                        sceneDetailsAdapter.setNewData(data);
                        NettyClient.getInstance().getApplianceStatus(AgentSharedPreferences.getMemberInfo(mBaseActivity).getMemberTelephone(), AgentSharedPreferences.getMemberInfo(mBaseActivity).getMemberDeviceId(), data);
                    }
                    break;
                //修改场景名称
                case 1002:
                    if (HttpUtils.getResultCode(object).equals(AgentConstants.RESULT_CODE_OK)) {
                        showToast(HttpUtils.getResultMessage(object));
                        common_head_title.setText(title);
                    } else {
                        showToast(HttpUtils.getResultMessage(object));
                    }
                    break;
                //删除场景
                case 1003:
                    if (HttpUtils.getResultCode(object).equals(AgentConstants.RESULT_CODE_OK)) {
                        showToast(HttpUtils.getResultMessage(object));
                        finish();
                    } else {
                        showToast(HttpUtils.getResultMessage(object));
                    }
                    break;
                //添加设备
                case 1004:
                    break;
                //删除设备
                case 1005:
                    if (HttpUtils.getResultCode(object).equals(AgentConstants.RESULT_CODE_OK)) {
                        showToast(HttpUtils.getResultMessage(object));
                        sceneDetailsAdapter.getDataList().remove(mPosition);
                        sceneDetailsAdapter.notifyItemRemoved(mPosition);//推荐用这个
                        if (mPosition != (sceneDetailsAdapter.getDataList().size())) { // 如果移除的是最后一个，忽略 注意：这里的mDataAdapter.getDataList()不需要-1，因为上面已经-1了
                            sceneDetailsAdapter.notifyItemRangeChanged(mPosition, sceneDetailsAdapter.getDataList().size() - mPosition);
                        }
                    } else {
                        showToast(HttpUtils.getResultMessage(object));
                    }
                    break;
                default:
                    break;
            }
        }
    }

    protected void getIntentData() {
        // 获取意图对象
        Intent intent = getIntent();
        //获取传递的值
        title = intent.getStringExtra("title");
        sceneMasterId = intent.getStringExtra("sceneMasterId");
    }

    protected void initCommonHeader() {
        common_head_more.setImageResource(R.mipmap.icon_more);
        configCommonHeader(this, title, true);
    }

    protected void initMoreData() {
        moreIconList.add(R.mipmap.icon_homepage_select);
        moreIconList.add(R.mipmap.icon_my_select);
        moreIconList.add(R.mipmap.icon_homepage_select);
        moreTitleList.add(getString(R.string.scene_title_change));
        moreTitleList.add(getString(R.string.scene_delete));
        moreTitleList.add(getString(R.string.device_add));
    }

    protected void initView() {
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        activity_scene_detail_list.setLayoutManager(mLayoutManager);
        sceneDetailsAdapter = new SceneDetailsAdapter(this, data);
        sceneDetailsAdapter.setOnSwipeClickListener(new SceneDetailsAdapter.OnSwipeClickListener() {
            @Override
            public void onClick(int position, boolean status) {
                if (status) {
                    controlApplianceStatus(sceneDetailsAdapter.getDataList().get(position).getDeviceId()
                            , sceneDetailsAdapter.getDataList().get(position).getApplianceId(), "10", null);
                } else {
                    controlApplianceStatus(sceneDetailsAdapter.getDataList().get(position).getDeviceId()
                            , sceneDetailsAdapter.getDataList().get(position).getApplianceId(), "20", null);
                }
            }

            @Override
            public void onDelete(final int position) {
                new CustomDialog.Builder(mBaseActivity)
                        .setTitle("智能家居")
                        .setMessage("要删除这个设备吗?")
                        .setButton(DialogInterface.BUTTON_POSITIVE, "删除", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mPosition = position;
                                DeviceModel deviceModel = sceneDetailsAdapter.getDataList().get(position);
                                deleteSceneAppliance(deviceModel.getMasterId());
                            }
                        })
                        .setButton(DialogInterface.BUTTON_NEGATIVE, "取消", null)
                        .setCancelable(false)
                        .create()
                        .show();
            }
        });
        activity_scene_detail_list.setAdapter(sceneDetailsAdapter);
    }

    public void getApplianceList() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("memberId", AgentSharedPreferences.getLastLoginId(mBaseActivity));
        jsonObject.put("sceneMasterId", sceneMasterId);
        jsonObject.put("type", "10");
        HttpUtils.post(mBaseActivity, 1001, ServerConstants.QUERY_APPLIANCE_LIST, jsonObject.toString(), mBaseActivity);
        startTipDialog(CustomTipDialog.ICON_TYPE_LOADING, getString(R.string.common_loading), true);
    }

    @OnClick(R.id.common_head_more)
    protected void moreClick() {
        final CustomPopupMenu.Builder builder = new CustomPopupMenu.Builder(this);
        builder.setIcon(moreIconList)
                .setTitle(moreTitleList)
                .isShowLine(true)
                .setItemLayoutParams(-2, -2)
                .setItemLayoutPadding(10, 10, 20, 20)
                .setContentView(common_head_more)
                .setOff(-(int) (common_head_more.getWidth() / DisplayHelper.DENSITY / 2.5), 0)
                .setOnMenuItemClickListener(new CustomPopupMenu.onMenuItemClickListener() {
                    @Override
                    public void onMenuItemClick(int itemPosition) {
                        switch (itemPosition) {
                            //修改场景名称
                            case 0:
                                EditDialog editDialog = new EditDialog(mBaseActivity);
                                editDialog.setOnAddClickListener(new EditDialog.OnAddClickListener() {
                                    @Override
                                    public void onAddClick(String name) {
                                        updateSceneName(name);
                                        title = name;
                                    }
                                });
                                editDialog.show();
                                break;
                            //删除场景
                            case 1:
                                new CustomDialog.Builder(mBaseActivity)
                                        .setTitle("智能家居")
                                        .setMessage("要删除这个场景吗?")
                                        .setButton(DialogInterface.BUTTON_POSITIVE, "删除", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                deleteScene();
                                            }
                                        })
                                        .setButton(DialogInterface.BUTTON_NEGATIVE, "取消", null)
                                        .setCancelable(false)
                                        .create()
                                        .show();
                                break;
                            //添加设备:sceneId为空的
                            case 2:
                                Bundle bundle = new Bundle();
                                bundle.putString("sceneMasterId", sceneMasterId);
                                startOtherActivity(SceneAddDeviceActivity.class, bundle);
                                break;
                            default:
                                break;
                        }
                        builder.dismiss();
                    }
                })
                .create()
                .show();
    }

    //修改场景名称
    protected void updateSceneName(String name) {
        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("memberId", AgentSharedPreferences.getLastLoginId(mBaseActivity));
        jsonObject.put("masterId", sceneMasterId);
        jsonObject.put("sceneName", name);
        HttpUtils.post(mBaseActivity, 1002, ServerConstants.UPDATE_SCENE_NAME, jsonObject.toString(), mBaseActivity);
        startTipDialog(CustomTipDialog.ICON_TYPE_LOADING, getString(R.string.common_changing), true);
    }

    //删除设备:把家电的sceneId update为空
    protected void deleteSceneAppliance(String masterId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("memberId", AgentSharedPreferences.getLastLoginId(mBaseActivity));
        jsonObject.put("masterId", masterId);
        jsonObject.put("sceneMasterId", sceneMasterId);
        HttpUtils.post(mBaseActivity, 1005, ServerConstants.DELETE_SCENE_APPLIANCE, jsonObject.toString(), mBaseActivity);
        startTipDialog(CustomTipDialog.ICON_TYPE_LOADING, getString(R.string.common_deleting), true);
    }

    //删除场景
    protected void deleteScene() {
        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("sceneMemberId", AgentSharedPreferences.getLastLoginId(mBaseActivity));
        jsonObject.put("masterId", sceneMasterId);
        HttpUtils.post(mBaseActivity, 1003, ServerConstants.DELETE_SCENE, jsonObject.toString(), mBaseActivity);
        startTipDialog(CustomTipDialog.ICON_TYPE_LOADING, getString(R.string.common_deleting), true);
    }

    @Override
    public void onResume() {
        super.onResume();
        getApplianceList();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(NettyBaseMsg nettyBaseMsg) {
        //家电状态根据对应的id处理
        NettyReplyStatusMsg nettyReplyStatusMsg = (NettyReplyStatusMsg) nettyBaseMsg;
        List<DeviceModel> list = nettyReplyStatusMsg.getList();
        for (int i = 0; i < sceneDetailsAdapter.getDataList().size(); i++) {
            for (int j = 0; j < list.size(); j++) {

                String mClientId = sceneDetailsAdapter.getDataList().get(i).getMemberId();
                String mDeviceId = sceneDetailsAdapter.getDataList().get(i).getDeviceId();
                String mApplianceId = sceneDetailsAdapter.getDataList().get(i).getApplianceId();

                String clientId = list.get(j).getMemberId();
                String deviceId = list.get(j).getDeviceId();
                String applianceId = list.get(j).getApplianceId();

                Log.d(TAG, "onEventMainThread: 列表applianceId=" + mApplianceId);
                Log.d(TAG, "onEventMainThread: 收到applianceId=" + applianceId);
                if (mClientId.equals(clientId)
                        && mApplianceId.equals(applianceId)) {
                    Log.d(TAG, "onEventMainThread: 对应的onlineStatus=" + list.get(j).getOnlineStatus());
                    Log.d(TAG, "onEventMainThread: 对应的status=" + list.get(j).getStatus());

                    sceneDetailsAdapter.getDataList().get(i).setOnlineStatus(list.get(j).getOnlineStatus() == null ? "20" : list.get(j).getOnlineStatus());
                    sceneDetailsAdapter.getDataList().get(i).setStatus(list.get(j).getStatus() == null ? "20" : list.get(j).getStatus());
                    sceneDetailsAdapter.notifyItemChanged(i);
                }
            }
        }
    }

    //控制设备
    protected void controlApplianceStatus(String deviceId, String applianceId, String status, String params) {
        String clientId = AgentSharedPreferences.getMemberInfo(mBaseActivity).getMemberTelephone();
        //组装 设备列表
        List<DeviceModel> list = new ArrayList<>();
        DeviceModel deviceModel = new DeviceModel();
        deviceModel.setMemberId(clientId);
        deviceModel.setDeviceId(deviceId);
        deviceModel.setApplianceId(applianceId);
        deviceModel.setStatus(status);
        if (params != null) {
            deviceModel.setParams(params);
        }
        list.add(deviceModel);
        //控制
        NettyClient.getInstance().controlApplianceStatus(clientId, deviceId, list);
    }
}
